<template>
  <div>
    <a-upload
      v-model:file-list="fileList"
      :accept="accept"
      :list-type="listType"
      :headers="headers"
      :show-upload-list="true"
      :custom-request="customRequest"
      :before-upload="beforeUpload"
      @change="change"
    >
      <div v-if="fileList.length < max" class="h-28 w-28 flex flex-col items-center justify-center">
        <loading-outlined v-if="loading"></loading-outlined>
        <plus-outlined v-else></plus-outlined>
        <div style="margin-top: 8px">{{ t("common.upload") }}</div>
      </div>
    </a-upload>
    <div v-if="fileList.length > 0">
      <a @click="handleClearAll"><delete-outlined /> {{ t("common.clear") }}</a>
    </div>
    <!-- <div class="text-color-secondary text-sm">{{ t("components.uploadImg.uploadTips") }}</div> -->
  </div>
</template>
<script lang="ts" setup>
import { ref, watch } from "vue";
import { LoadingOutlined, PlusOutlined, DeleteOutlined } from "@ant-design/icons-vue";
import env from "/@/base/env";
import { Api, uploadReq } from "/@/api/common";
import { IMG_EXT, isImgFile } from "/@/utils/file";
import { getAuthHeaderInfo, ResponseData } from "/@/api/req";
import { message } from "ant-design-vue";
import type { UploadChangeParam, UploadProps, UploadFile } from "ant-design-vue";
import { useI18n } from "/@/locales/useI18n";
import { BizType, StorageType } from "/@/types/components";
import { UploadListType } from "ant-design-vue/es/upload/interface";
import { UploadRequestError } from "ant-design-vue/es/vc-upload/interface";

const props = withDefaults(
  defineProps<{
    value?: string | Array<string | undefined>;
    width?: number;
    listType?: UploadListType;
    //是否手动上传 默认自动上传，即选择图片后马上上传
    manual?: boolean;
    // 业务类型
    bizType?: string;
    // 存储类型
    storageType?: string;
    max?: number;
    maxSize?: number;
  }>(),
  {
    listType: "picture-card",
    width: 150,
    max: 1,
    bizType: BizType.iot,
    storageType: StorageType.minio,
    maxSize: 2,
  }
);

const emits = defineEmits<{
  (event: "change", url: string | Array<string | undefined>);
  (event: "beforeUpload");
  (event: "upload");
}>();

const { t } = useI18n();
const handleClearAll = () => {
  fileList.value = [];
  emits("change", props.max > 1 ? [] : "");
};
const customRequest: UploadProps["customRequest"] = async (options) => {
  // console.log("=====>customRequest", options);
  let formData = new FormData();
  formData.append("file", options.file);
  // formData.append("bizType", props.bizType);
  // formData.append("storageType", props.storageType);
  let url = env.baseUrl + "/" + Api.upload;
  let req = await uploadReq(url, formData);
  if (req) {
    options.onSuccess && options.onSuccess(req);
    req.url && message.success(t("common.operSuccess"));
  } else {
    let obj: UploadRequestError = {
      status: 500,
      name: "",
      message: "上传失败",
    };
    fileList.value.splice(fileList.value.length - 1, 1);
    options.onError && options.onError(obj);
  }
};
const fileList = ref<Array<UploadFile<ResponseData>>>([]);
watch(
  () => props.value,
  () => {
    // 如value是undefined或者空数组 则清空
    if (!props.value || (props.value && Array.isArray(props.value) && props.value.length === 0)) {
      // handleClearAll();
      fileList.value = [];
    } else if (props.value && Array.isArray(props.value) && props.value.length > 0) {
      fileList.value = props.value.map((item, index) => {
        return {
          uid: index + "img",
          name: "imgs" + index,
          url: item,
          status: "done",
          type: "image/jpeg",
        };
      });
    } else if (props.value && !Array.isArray(props.value)) {
      fileList.value = [{ uid: "img1", name: "img", url: props.value }];
    }
  }
);
const accept = IMG_EXT;
const loading = ref(false);
const headers = getAuthHeaderInfo(true);
const beforeUpload: UploadProps["beforeUpload"] = (file) => {
  if (props.manual) {
    console.warn("手动上传功能开发中...", file);
    return false;
  }
  if (!isImgFile(file.name)) {
    message.info("请上传png/jpg/jpeg/gif格式的图片");
    return false;
  }
  const mb = file.size / 1024 / 1024;
  if (mb > props.maxSize) {
    message.info("请上传小于" + props.maxSize + "mb的文件");
    fileList.value = [];
    return false;
  }
  // if (props.manual) {
  //   console.warn("手动上传功能开发中...", file);
  //   return false;
  // }
  // let fileType = getFileType(file.name);
  // if (fileType !== "picture") {
  //   message.warning(t("components.uploadImg.uploadTips"));
  //   return false;
  // }
  // const mb = file.size / 1024 / 1024;
  // if (mb > props.maxSize) {
  //   message.warning("请上传小于" + props.maxSize + "mb的文件");
  //   return false;
  // }
  // console.log("===>file sizes", file.size);
  emits("beforeUpload");
};
const change = (info: UploadChangeParam<UploadFile<ResponseData>>) => {
  // console.log("change", info);
  if (info.file.status === "uploading") {
    loading.value = true;
    return;
  } else if (info.file.status === "done") {
    loading.value = false;
    emits("upload");
    const res = info.file.response;
    if (res && res.data) {
      let value: string | Array<string | undefined> = "";
      // fileList.value.map((item) => {
      //   return item.response && item.response.url;
      // });
      if (props.max > 1) {
        value =
          fileList.value.map((item) => {
            return item.url || (item.response && item.response.url);
          }) || [];
      } else {
        value = res.data.url;
      }
      emits("change", value);
    } else {
      message.error(t("common.uploadErr"));
    }
  } else if (info.file.status === "error") {
    loading.value = false;
    emits("upload");
    message.error(t("common.uploadErr"));
  } else if (info.file.status && info.file.status === "removed") {
    if (props.max > 1) {
      let imgArr =
        fileList.value.map((item) => {
          return item.url || (item.response && item.response.url);
        }) || [];
      emits("change", imgArr);
    } else {
      emits("change", "");
    }
  } else if (!info.file.status) {
    fileList.value = [];
    emits("change", []);
  }
};
</script>
<style lang="less"></style>
